﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

namespace JackProjectTemplate.Shared.Extensions
{
    public static class HttpContextExtentions
    {
        // https://devv.ai/zh/search?threadId=d9yulxnfrbwg
        public static string GetClientIPAddress(this HttpContext? httpContext)
        {
            if (httpContext == null) return string.Empty;

            // 获取X-Forwarded-For头的值
            var xForwardedFor = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(xForwardedFor)) return xForwardedFor;

            // 获取X-Real-IP头的值
            var xRealIP = httpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(xRealIP)) return xRealIP;

            // 获取客户端IP地址
            IPAddress ipAddress = httpContext.Connection.RemoteIpAddress;
            if (ipAddress.IsIPv4MappedToIPv6)
            {
                ipAddress = ipAddress.MapToIPv4();
            }
            var clientIPAddress = ipAddress.ToString();
            return clientIPAddress;
        }
    }
}
